package com.blackhorse.service.impl;

import com.blackhorse.domain.Order;
import com.blackhorse.domain.TxLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * 测试rocketmq事务消息，用于监听本地事务执行结果
 *
 * @author laizhe
 */
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
@Slf4j
@Service
public class OrderServiceImpl4Listener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderServiceImpl4 orderServiceImpl4;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //执行本地事务，message就是发送的半事务消息，arg就是发送时传入的最后一个参数
        try {
            //事务ID和订单参数
            String txId = (String) message.getHeaders().get("txId");
            Order order = (Order) arg;
            orderServiceImpl4.createOrder(txId, order);
            //本地事务执行成功，提交半事务消息
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("executeLocalTransaction error", e);
            //本地事务执行失败，回滚半事务消息
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //如果broker一直没有收到executeLocalTransaction的结果，则会查询本地事务结果，这里是查txLog表
        String txId = (String) message.getHeaders().get("txId");
        TxLog txLog = orderServiceImpl4.queryTxLog(txId);
        if (txLog != null) {
            //查到说明本地事务执行成功
            return RocketMQLocalTransactionState.COMMIT;
        }
        //不存在txLog，说明本地事务执行失败
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
